//
//  KChartViewController.m
//  Stock
//
//  Created by sun black on 11-7-27.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "KChartViewController.h"

@implementation KChartViewController
@synthesize service;
@synthesize dataArray;
@synthesize chartType;
@synthesize stockId;
@synthesize graph;
@synthesize hostView;
@synthesize xLabelTitles;
@synthesize loadingView;
@synthesize barChartData;

-(void) chartViewDidDisplay{
    if (loaded) {
        return;
    }
    [self.service queryDataWithChartType:self.chartType andStockId:self.stockId];
}


- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
}


-(void)requestFinishedWithResult:(id)aResult andUserinfo:(NSDictionary *)aUserinfo{
    loaded = YES;
    
    [loadingView removeFromSuperview];
    self.loadingView = nil;
    
    NSArray *newData = [aResult objectForKey:@"quotes"];
    
    NSArray *temp =[newData filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"amount!=0.0"]];
    /*NSMutableArray *temp2 = [NSMutableArray arrayWithArray:temp];
    NSMutableIndexSet *indexSet = [[NSMutableIndexSet alloc] init];
    for (int i=0; i<temp.count/2; i++) {
        [indexSet addIndex:i];
    }
    
    [temp2 removeObjectsAtIndexes:indexSet];
     NSLog(@"old.count=%d,new.count=%d",temp.count,temp2.count);
    */
    self.dataArray = [NSMutableArray arrayWithArray:temp];
    self.barChartData = [NSMutableArray array];
    
    int percent = [[aResult objectForKey:@"degree"] intValue];
    
    if (percent) {
        self.graph.plotAreaFrame.paddingRight = 290.0*(1-percent/100.0);
    }
    float maxTrade=0.0f,minTrade=0.0f,maxAmount=0.0f,minAmount=0.0f;
    for (int i=0;i<dataArray.count;i++) {
        NSDictionary *dict = [dataArray objectAtIndex:i];
        if (i%2==1) {
            NSMutableDictionary *tempDict = [NSMutableDictionary dictionary];
            float amount = /*(i-1)==0?0:*/[[[dataArray objectAtIndex:i-1] objectForKey:@"amount"] floatValue]+[[dict objectForKey:@"amount"] floatValue];
            NSLog(@"amount=%f",amount);
            [tempDict setValue:[NSString stringWithFormat:@"%f",amount] forKey:@"amount"];
            [barChartData addObject:tempDict];
        }
        float trade = [[dict objectForKey:@"trade"] floatValue];
        float amount = [[dict objectForKey:@"amount"] floatValue];
        //NSLog(@"amount=%f",amount);
        if (trade > maxTrade) {
            maxTrade = trade;
        }
        if (trade < minTrade || minTrade==0) {
            minTrade = trade;
        }
        if (amount > maxAmount) {
            maxAmount = amount;
        }
        if (amount < minAmount || minAmount==0) {
            minAmount = amount;
        }
        NSString *title = [dict objectForKey:@"ticktime"];
        if ([title rangeOfString:@":"].location != NSNotFound) {
            NSArray *dates = [title componentsSeparatedByString:@":"];
            NSMutableArray *array = [NSMutableArray arrayWithArray:dates];
            [array removeLastObject];
            [xLabelTitles addObject:[array componentsJoinedByString:@":"]];
            
        }else{
            [xLabelTitles addObject:title];
        }
    }
    if ([chartType isEqualToString:@"tq"]) {
        maxAmount=minAmount=0.0;
        for (NSDictionary *dict in barChartData) {
            float amount = [[dict objectForKey:@"amount"] floatValue];
            
            if (amount > maxAmount) {
                maxAmount = amount;
            }
            if (amount < minAmount || minAmount==0) {
                minAmount = amount;
            }
        }
    }
    
    NSLog(@"maxAmount=%f,minAmount=%f",maxAmount,minAmount);
    //K线
    float margin = maxTrade-minTrade;
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;
    
    //plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:[lowDisplayLocation decimalValue]) length:[lengthDisplayLocation decimalValue]];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(margin?minTrade-margin:minTrade-0.1) length:CPTDecimalFromFloat((2.2*margin)?:0.2)];
    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0f) length:CPTDecimalFromInteger([dataArray count])];
    
    
    
    
    //柱状图
    CPTXYPlotSpace *barSpace = (CPTXYPlotSpace *)[self.graph plotSpaceWithIdentifier:@"barSpace"];
    barSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(minAmount) length:CPTDecimalFromFloat(3*(maxAmount-minAmount))];
    barSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0f) length:CPTDecimalFromInteger([chartType isEqualToString:@"tq"]?barChartData.count:dataArray.count)];
    //NSLog(@"minAmount=%f,3*(maxAmount-minAmount)=%f",minAmount,3*(maxAmount-minAmount));
    
    int range = [dataArray count]/(percent? (int)MAX(1,percent*5/100.0):5);
    //坐标
    CPTXYAxisSet *axisSet = (CPTXYAxisSet *)self.graph.axisSet;
    axisSet.xAxis.orthogonalCoordinateDecimal = CPTDecimalFromFloat(margin?minTrade-margin:minTrade-0.1);
    axisSet.xAxis.majorIntervalLength = CPTDecimalFromInt(range);
    axisSet.xAxis.minorTicksPerInterval = 0;
    NSMutableArray *labels = [NSMutableArray array];
    int labelsCount = [dataArray count]/range;
    //NSLog(@"count=%d,labels=%d",[dataArray count],labelsCount);
    for (int i=0; i<labelsCount+1; i++) {
        NSString *title = @"";
        NSLog(@"range=%d,count-1=%d",i*range,[xLabelTitles count]-1);
        if ([xLabelTitles count]>0 && i*range<=[xLabelTitles count]-1) {
            title = [xLabelTitles objectAtIndex:i*range];
        }
        CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:title textStyle:axisSet.xAxis.labelTextStyle];
        NSNumber *tickLocation = [NSDecimalNumber numberWithInt:i*range];
		newLabel.tickLocation = [tickLocation decimalValue];
		[labels addObject:newLabel];
		[newLabel release];
    }
	axisSet.xAxis.axisLabels =  [NSSet setWithArray:labels];
    //NSLog(@"%f,%f",maxTrade,minTrade);
    float labelRange = 0.1;
    if (maxTrade-minTrade > 0.4) {
        labelRange = margin/3;
    }
    axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(labelRange);
    axisSet.yAxis.minorTicksPerInterval = 0;
    axisSet.yAxis.orthogonalCoordinateDecimal = CPTDecimalFromString(@"0.00");
    
	NSArray *exclusionRanges  = [NSArray arrayWithObjects:
								 [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0) length:CPTDecimalFromFloat(minTrade)],
								 nil];
	axisSet.yAxis.labelExclusionRanges = exclusionRanges;
    
    
    if (maxTrade>1000.0) {
        self.graph.plotAreaFrame.paddingLeft = 50.0f;
    }
    
    
    CPTScatterPlot *dataSourceLinePlot = (CPTScatterPlot *)[graph plotWithIdentifier:@"kPlot"];
    
    CPTColor *beginColor = [CPTColor colorWithComponentRed:1.0 green:1.0 blue:1.0 alpha:0.8];
    CPTColor *endColor = [CPTColor colorWithComponentRed:1.0 green:1.0 blue:1.0 alpha:0.3];
    CPTGradient *areaGradient = [CPTGradient gradientWithBeginningColor:beginColor endingColor:endColor];
    areaGradient.angle = -90.0f;
	CPTFill *areaGradientFill = [CPTFill fillWithGradient:areaGradient];
    dataSourceLinePlot.areaFill = areaGradientFill;
    dataSourceLinePlot.areaBaseValue = CPTDecimalFromDouble(minTrade-margin);
    
    [self.graph reloadData];
}
-(void)requestFinishedwithError:(NSError *)aError andUserinfo:(NSDictionary *)aUserinfo{
    
}



#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.xLabelTitles = [NSMutableArray array];
    
    self.service = [[[StockChartDataService alloc] initWithDelegate:self] autorelease];
    
    
    CPTGraphHostingView *newhostView = [[CPTGraphHostingView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:newhostView];
    self.hostView = newhostView;
    [newhostView release];
    [self buildChartGraph];
    
    [self.view bringSubviewToFront:loadingView];
    
}
-(void)buildChartGraph{
    
    self.graph = nil;
    
    CPTXYGraph *barChart = [[CPTXYGraph alloc] initWithFrame:self.view.bounds];
    [barChart applyTheme:[CPTTheme themeNamed:kCPTDarkGradientTheme]];
    
    self.graph = barChart;
    self.hostView.hostedGraph = barChart;
    
    barChart.plotAreaFrame.borderLineStyle = nil;
    barChart.plotAreaFrame.cornerRadius = 0.0f;
    
    barChart.paddingLeft = 0.0f;
    barChart.paddingRight = 0.0f;
    barChart.paddingTop = 0.0f;
    barChart.paddingBottom = 0.0f;
    
    barChart.plotAreaFrame.paddingLeft = 30.0f;
    barChart.plotAreaFrame.paddingRight = 0.0f;
    barChart.plotAreaFrame.paddingTop = 0.0f;
    barChart.plotAreaFrame.paddingBottom = 20.0f;
    
    
    // Axes
    CPTXYAxisSet *xyAxisSet = (id)graph.axisSet;
    CPTXYAxis *xAxis = xyAxisSet.xAxis;
    CPTMutableTextStyle *textStyle = [CPTTextStyle textStyle];
    textStyle.color = [CPTColor whiteColor];
    textStyle.fontSize = 9.0f;
    textStyle.textAlignment = CPTTextAlignmentCenter;
    xyAxisSet.xAxis.labelTextStyle = textStyle;
    xyAxisSet.yAxis.labelTextStyle = textStyle;  
    
    xAxis.axisLineStyle = nil;
    CPTXYAxis *yAxis = xyAxisSet.yAxis;
    CPTMutableLineStyle *ylineStyle = [CPTMutableLineStyle lineStyle];
    ylineStyle.lineWidth = 1.0f;
    ylineStyle.lineColor = [CPTColor darkGrayColor];
    yAxis.axisLineStyle = ylineStyle;
    //yAxis.hidden = YES;//.axisLineStyle = nil;
    
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;
    
    CPTScatterPlot *dataSourceLinePlot = [[[CPTScatterPlot alloc] initWithFrame:graph.bounds] autorelease];
    dataSourceLinePlot.identifier = @"kPlot";
    
    CPTMutableLineStyle *lineStyle = [[dataSourceLinePlot.dataLineStyle mutableCopy] autorelease];
    lineStyle.lineWidth = 1.f;
    lineStyle.lineColor = [CPTColor greenColor];//[CPTColor colorWithComponentRed:79/255.0 green:172/255.0 blue:164/255.0 alpha:1.0];
    dataSourceLinePlot.dataLineStyle = lineStyle;
    dataSourceLinePlot.dataSource = self;
    [barChart addPlot:dataSourceLinePlot toPlotSpace:plotSpace];
    
    
    
    
    
    //成交量柱状图
    CPTXYPlotSpace *barSpace = [[CPTXYPlotSpace alloc] init];
	barSpace.identifier = @"barSpace";
    [graph addPlotSpace:barSpace];
    [barSpace release];
	CPTBarPlot *barPlot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor yellowColor] horizontalBars:NO];
    barPlot.dataSource = self;
    
    lineStyle = [barPlot.lineStyle mutableCopy];
    lineStyle.lineColor = [CPTColor blackColor];
    barPlot.lineStyle = lineStyle;
    [lineStyle release];
    CPTFill *fill = [[CPTFill alloc] initWithColor:[CPTColor yellowColor]];
    barPlot.fill = fill;
    [fill release];
	barPlot.barWidth = CPTDecimalFromFloat(1.0f);
    barPlot.identifier = @"barPlot";
    [graph addPlot:barPlot toPlotSpace:barSpace];
	
    
    
    [barChart release];
}

#pragma mark -
#pragma mark Plot Data Source Methods

-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot {
    return [chartType isEqualToString:@"tq"]&&[plot.identifier isEqual:@"barPlot"]?barChartData.count:dataArray.count;
}

-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index 
{
    NSDictionary *dataCell = [dataArray objectAtIndex:index];
    NSDecimalNumber *num = nil;
    if ([plot.identifier isEqual:@"kPlot"]) {
        switch ( fieldEnum ) {
            case CPTScatterPlotFieldX:
                num = (NSDecimalNumber *)[NSDecimalNumber numberWithUnsignedInteger:index];
                break;
            case CPTScatterPlotFieldY:{
                if ([dataCell isEqual:[NSNull null]]) {
                    num = (NSDecimalNumber *)[NSDecimalNumber numberWithFloat:0.0f];
                }else{
                    float value = [[dataCell objectForKey:@"trade"] floatValue];
                    num = (NSDecimalNumber *)[NSDecimalNumber numberWithFloat:value];
                }
            }
            break;
        }
    }else{
        if (fieldEnum == CPTBarPlotFieldBarLocation) {
            num = (NSDecimalNumber *) [NSDecimalNumber numberWithInt:index];
        }else if (fieldEnum == CPTBarPlotFieldBarTip ) {
            if ([chartType isEqual:@"tq"]) {
                dataCell = [barChartData objectAtIndex:index];
            }
            if ([dataCell isEqual:[NSNull null]]) {
                num = (NSDecimalNumber *)[NSDecimalNumber numberWithFloat:0.0f];
            }else{
                float value = [[dataCell objectForKey:@"amount"] floatValue];
                num = (NSDecimalNumber *)[NSDecimalNumber numberWithFloat:value];
            }
        }

    }
    return num;
}

-(CPTFill *) barFillForBarPlot:(CPTBarPlot *)barPlot recordIndex:(NSNumber *)index; 
{
	return nil;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [service cancleAllRequest];
    self.service = nil;
    self.graph = nil;
    self.hostView = nil;
    self.xLabelTitles = nil;
    self.loadingView = nil;
}

-(void)dealloc{
    [service cancleAllRequest];
    self.service = nil;
    self.dataArray = nil;
    self.chartType = nil;
    self.stockId = nil;
    self.graph = nil;
    self.hostView = nil;
    self.xLabelTitles = nil;
    self.loadingView = nil;
    self.barChartData = nil;
    [super dealloc];
}

@end
